var express = require('express');
const {
  route
} = require('.');
var router = express.Router();
const userDao = require('../data/user')
const token = require('../jwt/jwt')

/* POST users listing. */
router.post('/login', async function (req, res, next) {
  let result = await userDao.onSelectOnlyUser(req.body)
  if (result.length === 0 || result.length >= 2) {
    let data = {
      status: 500,
      code: 10010,
      message: "当前用户暂无权限",
    }
    res.status(201).send(data)
    return
  } else {
    let rel = result[0]
    let authorization = token.encrypt({
      data: rel.id
    })
    rel['token'] = authorization
    let value = {
      status: 200,
      code: 0,
      message: "ok",
    }
    value['data'] = rel
    res.send(value)
    return
  }
});
router.post('/user/list', async function (req, res, next) {
  let result = await userDao.onSelectAllUser(req.body)
  if (result.data.length === 0) {
    let data = {
      status: 500,
      code: 10010,
      message: "暂无数据",
    }
    res.status(201).send(data)
    return
  } else {
    res.send(result)
    return
  }
})
router.get('/user/:id', async function (req, res, next) {
  let result = await userDao.onSelectOnlyInfo(req.params)
  if (result.length === 0 || result.length >= 2) {
    let data = {
      status: 500,
      code: 10010,
      message: "当前用户暂无权限",
    }
    res.status(201).send(data)
    return
  } else {
    let rel = result[0]
    let data = {
      status: 200,
      code: 0,
      message: "ok",
      data: rel
    }
    res.send(data)
    return
  }
})
router.get('/role/:id/menu', async function (req, res, next) {
  let result = await userDao.onSelectOnlyMenu(req.params)
  let children = []
  const father = result.filter(v => v.parent_Id === 0)
  for (let i = 0; i < father.length; i++) {
    children = []
    result.forEach(element => {
      if (father[i].id === element.parent_Id && element.parent_Id !== 0) {
        children.push(element)
      }
    });
    father[i].children = children
  }


  if (result.length === 0) {
    let data = {
      status: 500,
      code: 10010,
      message: "当前用户暂无权限",
    }
    res.status(201).send(data)
    return
  } else {
    let rel = father
    let data = {
      status: 200,
      code: 0,
      message: "ok",
      data: rel
    }
    res.send(data)
    return
  }
})
module.exports = router;